<template>
  <div class="map-container">
    <div class="search-input">
      <el-input
        v-model.trim="state.searchText"
        clearable
        maxlength="50"
        placeholder="请输入关键字"
        style="width: 300px"
      />
      <el-button type="primary" style="margin-left: 10px" @click="toSearch">
        确定
      </el-button>
    </div>
    <div id="positionMap" class="map" style="height: 450px" />

    <div class="select-info">
      <el-descriptions
        label-class-name="custom-description-label-140"
        :column="2"
        border
        :colon="true"
      >
        <el-descriptions-item>
          <template #label>定位经度</template>
          {{ state.selectItem.longitude }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>定位纬度</template>
          {{ state.selectItem.latitude }}
        </el-descriptions-item>
        <el-descriptions-item v-if="isNeedAddress">
          <template #label>定位详细地址</template>
          {{ state.selectItem.address }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="form-item-btn-group">
      <el-button type="default" @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确认</el-button>
    </div>
  </div>
</template>

<script setup>
import {
  shallowRef,
  computed,
  watch,
  ref,
  reactive,
  onMounted,
  onBeforeMount
} from 'vue'
import mapObj from '@/utils/mapKey.js'
window._AMapSecurityConfig = {
  securityJsCode: mapObj.securityJsCode
}
import areaCode from '@/components/pub-area/areaCode.js'
import AMapLoader from '@amap/amap-jsapi-loader'
const emit = defineEmits([
  'update:longitude',
  'update:latitude',
  'update:address',
  'cancel'
])
const props = defineProps({
  areaAddress: {
    type: String,
    default: ''
  },
  longitude: {
    type: String,
    default: ''
  },
  latitude: {
    type: String,
    default: ''
  },
  address: {
    type: String,
    default: ''
  },
  belongArea: {
    type: String,
    default: ''
  },
  isNeedAddress: {
    type: Boolean,
    default: false
  }
})
const map = shallowRef(null)

const state = reactive({
  AMap: null,
  autoOptions: {},
  selectItem: {
    latitude: '',
    longitude: '',
    address: ''
  },
  searchText: '',
  map: null,
  marker: null,
  search: null,
  geocoder: null
})

const initMap = () => {
  state.selectItem = {
    latitude: props.latitude,
    longitude: props.longitude,
    address: props.address
  }
  AMapLoader.load({
    key: mapObj.key, // 申请好的Web端Key，首次调用 load 时必填
    version: '2.0'
  }).then(AMap => {
    state.AMap = AMap
    map.value = new AMap.Map('positionMap', {
      //设置地图容器id
      viewMode: '3D', //是否为3D地图模式
      zoom: 15, //初始化地图级别
      center: [113.266887, 23.133306] //初始化地图中心点位置
    })

    // 加载高德插件
    AMap.plugin(['AMap.PlaceSearch', 'AMap.Geocoder'], () => {
      state.geocoder = new AMap.Geocoder({
        // city: '全国'
        city: '全国'
      })
      state.search = new AMap.PlaceSearch({
        map: map.value
      })
      state.search.on('markerClick', function (e) {
        state.marker && map.value.remove(state.marker)
        geocoderGetAddress(e.data.location.lng, e.data.location.lat)
      })
      // 回显点图标
      if (state.selectItem.latitude && state.selectItem.longitude) {
        // 已有选择点
        drawMarker(state.selectItem.longitude, state.selectItem.latitude)
      } else {
        getLngLatByAreaAddress(props.areaAddress)
        // 没有选择点默认进入所选择的区划区域
        // state.geocoder.getLocation(props.belongArea, function (status, result) {
        //   console.log('result', result)
        //   if (status === 'complete' && result.info === 'OK') {
        //     var lnglat = result.geocodes[0].location
        //     // result中对应详细地理坐标信息
        //     const position = new AMap.LngLat(lnglat.lng, lnglat.lat)
        //     state.marker = new AMap.Marker({
        //       position: position
        //     })
        //     state.selectItem.longitude = lnglat.lng || ''
        //     state.selectItem.latitude = lnglat.lat || ''
        //     state.selectItem.address = result.geocodes[0].formattedAddress || ''
        //     map.value.add(state.marker)
        //     map.value.setCenter(position)
        //   }
        // })
      }
    })

    // 添加点击事件
    map.value.on('click', onMapClick)
  })
}

// 根据areaAddress获取经纬度 添加mark标注
const getLngLatByAreaAddress = address => {
  state.geocoder.getLocation(address, function (status, result) {
    if (status === 'complete' && result.info === 'OK') {
      let lnglat = result.geocodes[0].location
      const position = new AMap.LngLat(lnglat.lng, lnglat.lat)
      state.marker = new AMap.Marker({
        position: position
      })
      state.selectItem.longitude = lnglat.lng || ''
      state.selectItem.latitude = lnglat.lat || ''
      state.selectItem.address = result.geocodes[0].formattedAddress || ''
      map.value.add(state.marker)
      map.value.setCenter(position)
      state.searchText = result.geocodes[0].formattedAddress
    }
  })
}
// 高德地图根据坐标获取地址
const geocoderGetAddress = (lng, lat) => {
  state.geocoder.getAddress([lng, lat], function (status, result) {
    if (status === 'complete' && result.info === 'OK') {
      state.selectItem.longitude = lng
      state.selectItem.latitude = lat
      state.selectItem.address = result.regeocode.formattedAddress
    }
  })
}

onBeforeMount(() => {
  initMap()
})
// 搜索地图
const toSearch = () => {
  state.search.search(state.searchText)
}
// 点击地图
const onMapClick = e => {
  const { lng, lat } = e.lnglat
  state.marker && map.value.remove(state.marker)
  if (state.search.render) {
    state.searchText = ''
    // state.search.render.markerList.clear()
  }
  drawMarker(lng, lat)
  geocoderGetAddress(lng, lat)
}

// 绘制地点marker
const drawMarker = (lng, lat) => {
  const longitude = lng
  const latitude = lat
  if (state.marker) {
    state.marker.setMap(null)
  }
  state.marker = new state.AMap.Marker({
    position: new state.AMap.LngLat(longitude, latitude),
    anchor: 'bottom-center'
  })
  // this.selectItem.longitude = lng
  // this.selectItem.latitude = lat
  map.value.add(state.marker)
  map.value.setZoomAndCenter(16, [longitude, latitude])
}

const confirm = () => {
  emit('update:longitude', state.selectItem.longitude)
  emit('update:latitude', state.selectItem.latitude)
  emit('update:address', state.selectItem.address)
  emit('cancel')
}

const cancel = () => {
  emit('cancel')
}
</script>

<style lang="scss" scoped>
.search-input {
  position: absolute;
  left: 30px;
  top: 60px;
  z-index: 1;
  display: flex;
  align-items: center;
}
.select-info {
  margin-bottom: 45px;
}
</style>
